package com.cjj.common.facade.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cjj.common.consts.MenuTypeConst;
import com.cjj.common.dao.master.*;
import com.cjj.common.entity.dto.security.MenuRole;
import com.cjj.common.entity.po.master.*;
import com.cjj.common.facade.UserFacadeService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author by BrownC_
 * @date 2021/12/20 16:57:44
 * @email ccc-ju@outlook.com
 */
@Service
@RequiredArgsConstructor
public class UserFacadeServiceImpl implements UserFacadeService {

    private final ICUserService userService;

    private final ICRoleService roleService;

    private final ICUserRoleService userRoleService;

    private final ICRolePermissionService rolePermissionService;

    private final ICPermissionService permissionService;

    @Override
    public CUser getUserInfo(Long id) {
        return userService.getById(id);
    }

    @Override
    public CUser loadUserByUserName(String userName) {
        return userService.getOne(Wrappers.<CUser>lambdaQuery()
                .eq(CUser::getUsername, userName)
                .or()
                .eq(CUser::getMobile, userName)
                .or()
                .eq(CUser::getEmail, userName));
    }

    @Override
    public List<CRole> getRoleInfoByUid(Long uid) {
        List<Integer> roleIds = userRoleService.list(Wrappers.<CUserRole>lambdaQuery()
                .eq(CUserRole::getUid, uid)
                .select(CUserRole::getRoleId)).stream().map(CUserRole::getRoleId).collect(Collectors.toList());
        if(CollectionUtil.isEmpty(roleIds)){
            return null;
        }
        List<CRole> roles = roleService.list(Wrappers.<CRole>lambdaQuery()
                .in(CRole::getId, roleIds));
        return roles;
    }

    /**
     * 根据角色信息查询该用户所有的可用权限（不包括菜单, 菜单不在权限过滤范围之内）
     * @param roleIds 角色ID
     * @return
     */
    @Override
    public List<CPermission> getPermissionsByRoleId(List<Long> roleIds) {
        Set<Long> permissionIds = rolePermissionService.list(Wrappers.<CRolePermission>lambdaQuery()
                .in(CRolePermission::getRoleId, roleIds)
                .select(CRolePermission::getPermissionId)).stream().map(CRolePermission::getPermissionId).collect(Collectors.toSet());
        return permissionService.list(Wrappers.<CPermission>lambdaQuery()
                .in(CPermission::getId, permissionIds)
                .eq(CPermission::getMenuType, MenuTypeConst.BUTTON));
    }

    @Override
    public List<MenuRole> getMenuRoles() {
        return permissionService.getAllMenus();
    }
}
